<template>
  <el-dialog
    v-bind="config__"
    :before-close="onCancel">

    <!-- 内容 -->
    <el-form ref="form" :model="data__" label-width="80px" label-position="top">
      <el-form-item label="请填写日历库存" prop="stockRemain" verify>
        <SafeInputNumber v-model="data__.stockRemain" :maxlength="8" :min="0" :max="10000000"/>
      </el-form-item>

      <form-item-tip>该批量初始化日历库存只对选中的未设置过日历库存的日期有效。已设置过日历库存的，请修改日历库存余量</form-item-tip>
    </el-form>

    <!-- 页脚 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onOk" :loading="config__.loading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      config__: {
        top: '30vh',
        width: '450px',
        visible: false,
        appendToBody: true,
        title: '批量设置日历库存',
        closeOnClickModal: false,
        loading: false
      },
      data__: {
        openParams: []
      }
    }
  },
  mounted () {
    this.$bus.on('global:batch-stock-edit:open', this.onOpen)
  },
  beforeDestroy () {
    this.$bus.off('global:batch-stock-edit:open', this.onOpen)
  },
  methods: {
    onOk () {
      this.$refs.form.validate(valid => {
        if (valid) {
          const match = Array.from(this.data__.openParams.selectedSelections).map(date => ({
            useDate: date,
            stockRemain: parseInt(this.data__.stockRemain)
          }))


          this.config__.loading = true
          return this.$POST('/sot-admin-api/product/repertory/updateBatchCalendarStock', {
            productId: this.data__.openParams.productId,
            items: match
          }).then(_ => {
            this.$swal.success('批量初始化日历库存成功')
            this.$bus.emit('ticket-stock-calendar:refresh')
            this.$bus.emit('ticket-stock-calendar:clearAllSelect')
            this.onCancel()
          }).finally(_ => {
            setTimeout(_ => { this.config__.loading = false }, 300)
          })
        }
      })
    },
    onOpen (openParams) {
      this.data__.openParams = openParams
      this.config__.visible = true
    },
    onCancel () {
      this.config__.visible = false
      Object.assign(this.$data, this.$options.data.call(this))
    }
  },
}
</script>
